﻿using System;
using System.Data;
using System.Data.SqlClient;
using Common;

namespace DataAccess
{
    public class CommentDao
    {
        private SqlConnection _sqlConnection;
        public CommentDao()
        {
            _sqlConnection = SqlTools.GetConnection();
        }

        /// <summary>
        /// Views all comments.
        /// </summary>
        /// <returns></returns>
        public DataTable ViewAllComments(int postId)
        {
            try
            {
                var parameter = new SqlParameter("@PostId", SqlDbType.Int) {Value = postId};
                DataSet dataSet = SqlHelper.ExecuteDataSet(_sqlConnection, CommandType.Text, SqlQuery.ViewComments, parameter);
                return dataSet.Tables[0];
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        /// <summary>
        /// Adds the comment.
        /// </summary>
        /// <param name="name">The name.</param>
        /// <param name="comment">The comment.</param>
        /// <param name="date">The date.</param>
        /// <param name="postId">The post id.</param>
        /// <returns></returns>
        public int AddComment(string name, string comment, DateTime date, int postId)
        {
            try
            {
                var parameters = new SqlParameter[4];
                parameters[0] = new SqlParameter("@UserComment", SqlDbType.Text) { Value = name };
                parameters[1] = new SqlParameter("@CommentContent", SqlDbType.Text) {Value = comment};
                parameters[2] = new SqlParameter("@CmtDate", SqlDbType.DateTime) { Value = date };
                parameters[3] = new SqlParameter("@PostId",SqlDbType.Int) { Value = postId };
                return SqlHelper.ExecuteNonQuery(_sqlConnection, CommandType.Text, SqlQuery.AddComment, parameters);
            }
            catch (Exception)
            {
                
                throw;
            }
        }

        /// <summary>
        /// Deletes the comment by post id.
        /// </summary>
        /// <param name="postId">The post id.</param>
        /// <returns></returns>
        public int DeleteCommentByPostId(int postId)
        {
            try
            {
                var parameter = new SqlParameter("@PostId", SqlDbType.Int) {Value = postId};
                return SqlHelper.ExecuteNonQuery(_sqlConnection, CommandType.Text, SqlQuery.DeleteCommentByPostId,
                                                 parameter);
            }
            catch (Exception)
            {
                
                throw;
            }
        }
    }
}
